$(function(){

    console.log("准备完毕");
	const body_loading = new loadion('#londing_body')

//---------------------------------请求数据库begin--------------------------------------

    if(lsa.get('zmitem') == null){
        wxCloud.getzanmeiitem(function (res){
            lsa.set('zmitem',JSON.stringify(res))
        })
    }


        // getSaoErZmLists
//---------------------------------请求数据库end--------------------------------------


//--------------------------------选择激活样式begin--------------------------------
    $(".ad_nav ul li").click(

        function (){

                var left = $(this).width() * $(this).index() +'px'
                $(".ver_active").css('left',left)

        }
    )

//--------------------------------选择激活样式end--------------------------------



//--------------------------------服务器url初始化begin--------------------------------







//--------------------------------服务器url初始化end--------------------------------






//--------------------------------花园花朵表格begin--------------------------------



get_hd_db.gethdlist(1,300,20211231,20210901, (res)=>{


	body_loading.show()

    let newData = res.result.list.data

    lsa.set('srrz_item',JSON.stringify(newData))

    createHdTable(newData)
	body_loading.hide()




})




function createHdTable(newData){


    $("#hd_table").bootstrapTable({

        columns:[

            {
                field:'_id',
                title:'ID'
            },
            {
                field:'title',
                title:'标题'
            }
        ],
        data:newData,
        pagination:true,
        pageSize:5,
        clickToSelect: true,
        toolbar:"#toolbar",
        toolbarAlign:"right",
		onDblClickRow:function(row){
			edit(row)
		},
		onClickRow:function(row){
			edit(row)
		},
		onAll:function(name,args){

		}
    })




}



const edit_modal = new bootstrap.Modal($('#staticBackdrop')[0])

const SERVERURL = "https://7372-srrz-2g24l1oea7a7e67e-1304952114.tcb.qcloud.la/"

//单击花朵编辑事件
function edit(row){



	wxCloud.db().collection('flower-garden-list')
	.doc(row._id)
	.get()
	.then(res=>{
		// 渲染花朵编辑弹窗
		xuanranHd_tanChuang(res.data)
		createUploadTog("#ch_audioUrl","#Ch_audio_box",'#Ch_audio_loading',"audio/CH/",row._id+".mp3",true)
		createUploadTog("#en_audioUrl","#En_audio_box",'#En_audio_loading',"audio/EN/",row._id+".mp3",true)
	})


//------------------------添加经文选择事件begin--------------------------------------------------

    $("#jw").change(function (){

        let e = "#jw_id option[value=\""+ this.value +"\"]"

        $(this).attr( "data-id" , $(e).data()['id'] )

        $("#jw_context").text($(e).data()['context'])

        $("#jw_box").show()

    })

//-----------------------------添加经文选择事件end--------------------------------------

//------------------------添加首页图片选择事件begin--------------------------------------------------

   $("#hd_img_index_list").change(function (){

	   let hd_img_index_loading = new loadion("#hd_img_index_loading")

	   hd_img_index_loading.show()

	   let a = JSON.parse(lsa.get('hd_index_img')).filter(n=>n.title==$(this).val())

	   if(a.length==0){

		   $("#hd_index_img").hide()
		   hd_img_index_loading.hide()
		   $(this).attr('data-id','')
		   return
	   }
	   $(this).attr('data-id',a[0]['url'])

       $("#hd_index_img").attr( "src" , a[0]['url'] )

	   $("#hd_index_img")[0].onload = function(){
		   hd_img_index_loading.hide()
		   $("#hd_index_img").show()
	   }
   })

//-----------------------------添加首页图片选择事件end--------------------------------------

    edit_modal.show()

}

// -----------------------------首页图片上传功能begin -----------------------------
createUploadTog(
"#indexImage",
"#index_img",
'#index_img_loading',
"img/index/",
false)
$("#imgIndexSubmit").click(function(){
	let url = $('#index_img').attr('src')
	let title = $('#indexImage_title').val()
	console.log('url=>',url)
	console.log('title=>',title)
	if(url==''){
		alert('请选择图片')
		return
	}
	if(title==''){
		alert('请输入图片名称')
		return
	}
	let data = {url,title}
	wxCloud.db().collection('flower-garden-index-img')
	.add({
		data
	})
	.then(res=>{
		console.log('数据上传成功=>',res)
		data['_id'] = res['_id']
		console.log(data)
		let yuanlai = JSON.parse(lsa.get('hd_index_img'))
		let a = [...yuanlai,data]
		lsa.set('hd_index_img',JSON.stringify(a))
		alert('图片上传成功')

	})
	.catch(err=>{
		console.log('数据上传失败=>',err)
	})

})
// -----------------------------首页图片上传功能end -----------------------------

//关闭编弹窗事件
$("#close_edit_modal").click(function (){

    edit_modal.hide()
})
//提交事件
$("#submit_edit").click(function(){


	let loding = new loadion("#submit_loading")
    let hd_forms = $('#hd_form')[0]['elements']
    let submitData = {}
    submitData['wrapper']=[]
    let hd_id = $("#hd_title").attr("data-id")
    let uploadFileArr=[]
    hd_forms.forEach(i=>{
        switch(i.name){
            case 'title':
                submitData['_id'] = $(i).attr("data-id")
                submitData['title'] = i.value
            break
            case'zm_Id':
                console.log()
                submitData['zm_Id'] = $(i).attr("data-id")
            break;
            case'jw_Id':
                submitData['jw_Id'] = $(i).attr("data-id")
            break;
            case 'hd_img_url':


                    if($(i).attr("data-id") == ""){
                        submitData['indexImage'] = ""
                    }else{
                        submitData['indexImage'] = $(i).attr("data-id")
                    }

            break;
            case 'ch_audioUrl':


                    if($(i).attr("data-id") == ""){
                        submitData['wrapper'][0] = {audioUrl:"",title:"每日话语",imgUrl:`img/prayerJournalCH/${hd_id}.jpg`,sort:1}
                    }else{
                        submitData['wrapper'][0] = {audioUrl:$(i).attr("data-id"),title:"每日话语",imgUrl:`img/prayerJournalCH/${hd_id}.jpg`,sort:1}
                    }

            break;
            case 'en_audioUrl':

                    if($(i).attr("data-id") == ""){
                        submitData['wrapper'][1] = {audioUrl:"",title:"Todays Words",imgUrl:`img/prayerJournalEN/${hd_id}.jpg`,sort:2}
                    }else{
                        submitData['wrapper'][1] = {audioUrl:$(i).attr("data-id"),title:"Todays Words",imgUrl:`img/prayerJournalEN/${hd_id}.jpg`,sort:2}
                    }


            break;
        }
    })

	up_hd_itme(submitData["_id"],submitData)
	.then(res=>{
	    loding.hide()
		alert('数据上传成功')
		location.reload()
	    console.log("更新数据成功=>",res)
	})
	.catch(erro=>{
	    loding.hide()
		alert('数据失败')
	    console.log("更新数据失败=>",erro)
	})


})





//--------------------------------花园花朵表格end--------------------------------


//--------------------------------上传文件函数begin--------------------------------

//上传文件接口
function uploadFile(file,filePath,fileName=""){


    return wxCloud.cloud().uploadFile({
      cloudPath: filePath+fileName,
      file: file
    })

}

//更新花朵数据接口
function up_hd_itme(_id,data){
    console.log("_id=>",parseInt(_id))
    delete data['_id']
   return wxCloud.db()
    .collection("flower-garden-list")
    .doc(parseInt(_id))
    .update({data})

}
//新增花朵数据接口
function ad_hd_itme(data){

   return wxCloud.db()
    .collection("flower-garden-list")
    .add({data:data})

}
//获取封面首页接口API
function get_hd_index_img(){
	return wxCloud.db()
	 .collection("flower-garden-index-img").skip(10).limit(20).get()
}

//loading对象
function loadion(ele) {

    this.ele = ele
}

loadion.prototype.show=function(){

    $(this.ele).css("display","inline-block")
}
loadion.prototype.hide=function(){

    $(this.ele).css("display","none")
}

//上传文件显示媒体和赋值功能
function createUploadTog(e,e_box,loadinge,filePath,fileName,isAudio=false,fun){

	let loadion_index_img = new loadion(loadinge)
    $(e).change(function(){

        loadion_index_img.show()
        let file = $(this)[0].files[0]
		console.log(file)
		console.log(fileName)
		if(!fileName){
			console.log(fileName)
			var fileNames = file.name

		}else{
			var fileNames = fileName
		}

        uploadFile(file,filePath,fileNames)
		.finally(res=>{

			qieHuan(e,e_box,isAudio,fileNames)
		})

    })

	//文件上传成功后进行音频或图片切换为展示的
	function qieHuan(e,e_box,isAudio,fileName){

			let sign =new Date().getTime()

			let url = SERVERURL + filePath + fileName + "?sign=" + sign

			console.log(url)

			if(isAudio){

				// console.log("执行了加音频元素->",e_box +" audio")

				$(e_box +" audio").attr("src",url)
				$(e).attr("data-id",url.replace(SERVERURL,""))

			}else{

				$(e_box).attr("src",url)
				$(e).attr("data-id",url)
			}


			$(e_box).show()
			loadion_index_img.hide()

	}





}


//渲染花朵的弹窗功能
function xuanranHd_tanChuang(row){

		$("#hd_title").val(row.title)

		$("#hd_title").attr("data-id",row._id)

		let zm_a = JSON.parse(lsa.get('zmitem')).filter(n=>n._id==row.zm_Id)[0]

		let jw_a = JSON.parse(lsa.get('jw')).filter(n=>n._id==row.jw_Id)[0]

		server_config_url()
		.then(res=>{

			let {zmUrl,hdDmt} = res
			//赞美
			if(zm_a!==undefined){

				$("#zm").val(`${zm_a.xuhao}.${zm_a.mulu}`)
				$("#zm").attr('data-id',zm_a._id)
				var url = zmUrl+jm(`${zm_a.xuhao}${zm_a.mulu}`)+".mp3"
				$("#zm_audio").attr("src",url)
				$("#zm_box").show()

			}else{

				$("#zm").val(``)
				$("#zm_audio").attr("src","")
				$("#zm").attr('data-id',"")
				$("#zm_box").hide()
			}

			//经文

			if(jw_a!==undefined){

				$("#jw").val(jw_a['chTitle'])
				$("#jw_context").text(jw_a['chContext'])
				$("#jw").attr("data-id",jw_a._id)
				$("#jw_box").show()
			}else{

				$("#jw").val("")
				$("#jw_context").text("")
				$("#jw").attr("data-id","")
				$("#jw_box").hide()

			}

			//首页图片

			// ---------------------------渲染首页图片列表begin------------------------------------------------



				let hd_img_index_img = JSON.parse(lsa.get('hd_index_img'))
				let index_img_htm ="<option data-id=\"0\" data-url=\"0\">请选择首页图片</Option>"
				hd_img_index_img.forEach(function(item){

					index_img_htm+=`<option data-id="${item['_id']}" data-url="${item['url']}">${item['title']}</Option>`
				})

				$("#hd_img_index_list").html(index_img_htm)



			// ---------------------------渲染首页图片列表end------------------------------------------------


			if(row.indexImage!==""){
				let a = JSON.parse(lsa.get('hd_index_img')).filter(n=>{

					let reg = /(?<=\/index\/).+(\.jpg|\.jpeg|\.png)/

					if(n.url.match(reg) !== null){

						if(row.indexImage.match(reg)[0] == n.url.match(reg)[0]){
							return n
						}
					}
				})

				$("#hd_img_index_list").val(a[0].title)
				$("#hd_img_index_list").attr("data-id",row.indexImage)
				$("#hd_index_img").attr("src",row.indexImage)
				$("#hd_index_img").show()

			}else{

				$("#hd_img_index_list").attr("data-id","")
				$("#hd_index_img").attr("src","")
				$("#hd_index_img").hide()
			}

			//中文音频

			if(row.wrapper[0].audioUrl!==""){
				$("#Ch_audio").attr("src",hdDmt + row.wrapper[0].audioUrl)
				$("#ch_audioUrl").attr("data-id",row.wrapper[0].audioUrl)
				$("#Ch_audio_box").show()
			}else{

				$("#ch_audioUrl").attr("data-id","")
				$("#Ch_audio").attr("src","")
				$("#Ch_audio_box").hide()
			}

			//中文图片

			if(row.wrapper[0].imgUrl!==""){
				$("#Ch_img_box img").attr("src",hdDmt + row.wrapper[0].imgUrl)

				$("#Ch_img_box").show()
			}else{
				$("#Ch_img_box img").attr("src","")
				$("#Ch_img_box").hide()
			}


			//英文音频

			if(row.wrapper[1].audioUrl!==""){

				$("#En_audio").attr("src",hdDmt + row.wrapper[1].audioUrl)
				$("#en_audioUrl").attr("data-id",row.wrapper[1].audioUrl)
				$("#En_audio_box").show()

			}else{

				$("#En_audio").attr("src","")
				$("#en_audioUrl").attr("data-id","")
				$("#En_audio_box").hide()
			}

			//英文图片

			if(row.wrapper[1].imgUrl!==""){

				$("#En_img_box img").attr("src",hdDmt + row.wrapper[1].imgUrl)
				$("#En_img_box").show()
			}else{
				$("#En_img_box img").attr("src","")
				$("#En_img_box").hide()
			}

			//赞美选择
			$("#zm").change(function (){

			    let e = "#zm_id option[value=\""+ this.value +"\"]"
			    var url = zmUrl+jm($(e).data()['url'])+".mp3"

			    $(this).attr( "data-id" , $(e).data()['id'] )

			    $("#zm_audio").attr("src",url)
			    $("#zm_box").show()

			})

	})


}
//--------------------------------上传文件函数end--------------------------------


//-------------------------选择菜单begin-------------------------------
    setTimeout(()=>{

        //---------------------------渲染编辑框赞美列表begin-----------------------------------------------
        const zmitem = JSON.parse(lsa.get('zmitem'))
        const srzm = zmitem.filter(n=> n.shijiIndex == 3)
        let zm_item =""
        srzm.forEach(function (item){
            zm_item += `<option data-id="${item['_id']}" data-url="${item.xuhao}${item.mulu}"  value="${item.xuhao}.${item.mulu}">`
        })

        $("#zm_id").html(zm_item)
        //-----------------------------渲染编辑框赞美列表end---------------------------------------------

        //--------------------------渲染编辑框经文列表begin------------------------------------------------

		wxCloud.cloud().callFunction({
		    name:"getJingWeng"
		}).then(res=>{

			let data = res.result.data
			lsa.set('jw',JSON.stringify(data))
			const jingWen = JSON.parse(lsa.get('jw'))
			let jw_html = ""
			jingWen.forEach(function (item){
			    jw_html+= `<option data-id="${item['_id']}" data-context="${item['chContext']}" value="${item['chTitle']}">        `
			})

			$("#jw_id").html(jw_html)

		})


        //---------------------------渲染编辑框经文列表end-----------------------------------------------


		// ---------------------------渲染首页图片列表begin------------------------------------------------

			get_hd_index_img()
			.then(res=>{
				lsa.set('hd_index_img',JSON.stringify(res.data))
			})


		// ---------------------------渲染首页图片列表end------------------------------------------------

	},2000)

})
